package com.heima.behavior.service.impl;

import com.heima.behavior.model.dto.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.behavior.util.AppUserThreadLocalUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 判断用户是否登录
        boolean islike = false, isunlike = false, iscollection = false, isfollow = false;

        ApUser user = AppUserThreadLocalUtil.get();
        if (user != null) {
            //2.1 用户已经登录, 查询对应行为的状态
            //2.2.1 用户关注行为
            String user_follow_key = "USER_FOLLOW_" + user.getId();
            isfollow = stringRedisTemplate.opsForHash().hasKey(user_follow_key, dto.getAuthorId() + "");

            //2.2.2 用户点赞行为
            String user_like_key = "USER_LIKE_" + dto.getArticleId();
            islike = stringRedisTemplate.opsForHash().hasKey(user_like_key, user.getId() + "");

            //2.2.3 TODO 用户收藏行为
            //2.2.4 TODO 用户不喜欢行为
        }
        //2.2 用户没有登录, 所有状态返回默认值即可

        //3. 封装数据返回
        Map<String, Boolean> result = new HashMap<>();
        result.put("islike", islike);
        result.put("isunlike", isunlike);
        result.put("iscollection", iscollection);
        result.put("isfollow", isfollow);

        return ResponseResult.okResult(result);
    }
}
